using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Windows.Forms;
using System.ComponentModel;

namespace Controladoras
{
    public class CorreoElectronicoMantenedor
    {
        private static CorreoElectronicoMantenedor instancia;

        public static CorreoElectronicoMantenedor ObtenerInstancia()
        {
            if (instancia == null)
            {
                instancia = new CorreoElectronicoMantenedor(); 
            }
            return instancia;
        }

        //Constructor de la clase
        private CorreoElectronicoMantenedor()
        {
        }

        public void SendMail(String sTo, String sFrom, String sPassword, String sFromName, String sSubject, String sBody, String sHost)
        {
            //Builed The MSG
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.To.Add(sTo);
            //msg.To.Add("another.reciver@yahoo.com");
            msg.From = new MailAddress(sFrom, sFromName, System.Text.Encoding.UTF8);
            msg.Subject = sSubject;
            msg.SubjectEncoding = System.Text.Encoding.UTF8;
            msg.Body = sBody;
            msg.BodyEncoding = System.Text.Encoding.UTF8;
            msg.IsBodyHtml = false;
            msg.Priority = MailPriority.High;

            //Add the Creddentials
            SmtpClient client = new SmtpClient();
            client.Credentials = new System.Net.NetworkCredential(sFrom, sPassword);
            client.Port = 587;//or use 465            
            client.Host = sHost;
            client.EnableSsl = true;
            client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
            object userState = msg;
            try
            {
                //you can also call client.Send(msg)
                client.SendAsync(msg, userState);
            }
            catch (System.Net.Mail.SmtpException ex)
            {
                Console.WriteLine("Send Mail Error: " + ex.Message);
            }
        }

        void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            MailMessage mail = (MailMessage)e.UserState;
            string subject = mail.Subject;

            if (e.Cancelled)
            {
                string cancelled = string.Format("[{0}] Envio Cancelado.", subject);
                MessageBox.Show(cancelled);
            }
            if (e.Error != null)
            {
                string error = String.Format("[{0}] {1}", subject, e.Error.ToString());
                MessageBox.Show(error);
            }
            else
            {
                Console.WriteLine("Mensaje Enviado");
            }
            //mailSent = true;
        }
    }
}
